package org.pearl.springbootsecurity.demo.security.sms;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.pearl.springbootsecurity.demo.entity.Permission;
import org.pearl.springbootsecurity.demo.entity.Role;
import org.pearl.springbootsecurity.demo.pojo.UserInfoDO;
import org.pearl.springbootsecurity.demo.security.MyUser;
import org.pearl.springbootsecurity.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by TD on 2021/8/18
 * 查询短信登录信息并封装为UserDetails  这里可以抽取一个抽象类，权限加载和校验租户等逻辑交给父类处理
 */
@Service("smsUserDetailsService")
public class SmsUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * @param phone 手机号
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        // 1. 数据库查询手机用户,这里需要写根据手机号查询用户信息，这里写死吧。。。
        UserInfoDO userInfoDO = userService.getUserInfoByName("test");
        if (userInfoDO == null) {
            throw new UsernameNotFoundException("手机号不存在！");
        }
        // 2. 设置权限集合，后续需要数据库查询
/*        List<GrantedAuthority> authorityList =
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");*/
        // 2. 角色权限集合转为  List<GrantedAuthority>
        List<Role> roleList = userInfoDO.getRoleList();
        List<Permission> permissionList = userInfoDO.getPermissionList();
        List<GrantedAuthority> authorityList = new ArrayList<>();
        roleList.forEach(e -> {
            String roleCode = e.getRoleCode();
            if (StringUtils.isNotBlank(roleCode)) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleCode);
                authorityList.add(simpleGrantedAuthority);
            }
        });
        permissionList.forEach(e -> {
            String code = e.getCode();
            if (StringUtils.isNotBlank(code)) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code);
                authorityList.add(simpleGrantedAuthority);
            }
        });
        // 3. 返回自定义的用户信息
        MyUser myUser = new MyUser(userInfoDO.getUserName(), userInfoDO.getPassword(), authorityList);
        // 设置自定义扩展信息
        myUser.setDeptId(userInfoDO.getOrganizationId());
        myUser.setLoginTime(new Date());
        return myUser;
    }
}

